package com.qf.game.application.controller;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * 音频的controller
 */
@RestController
@CrossOrigin
public class AudioController {

    /**
     * 上传的音频文件的位置
     */
    private String path = "D:\\audio\\";

    /**
     * 上传音频
     * @return
     */
    @RequestMapping("/audio/upload")
    public String uploaderAudio(MultipartFile file){
        //准备一个上传的音频文件名称
        String fileName = UUID.randomUUID().toString();
        try (
                InputStream in = file.getInputStream();
                OutputStream out = new FileOutputStream(path + fileName);
        ){
            IOUtils.copy(in, out);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return fileName;
    }

    /**
     * 获取音频文件
     * @param filename
     */
    @RequestMapping("/audio/get")
    public void getAudio(String filename, HttpServletResponse response){
        try (
                InputStream in = new FileInputStream(path + filename);
                ServletOutputStream out = response.getOutputStream();
        ) {
            IOUtils.copy(in, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
